﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DisplayUI;
using System.IO;
using ESRI.ArcGIS.Analyst3D;
using System.Runtime.InteropServices;

namespace MyMap
{
    public partial class MyMap : Form
    {
        public MyMap()
        {
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);
            InitializeComponent();
        }
        private int m_iMouseFlag = 0;
        private string m_szFieldName = null;


        private void MyMap_Load(object sender, EventArgs e)
        {
          
            
                axTOCControl1.SetBuddyControl(axMapControl1);
            

        }



        private void AddShpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "shapefile文件（*.shp）|*.shp";

            DialogResult dialogResult = openFileDialog.ShowDialog();
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            string path = openFileDialog.FileName;
            string folder = System.IO.Path.GetDirectoryName(path);
            string fileName = System.IO.Path.GetFileName(path);

            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace workspace = workspaceFactory.OpenFromFile(folder, 0);
            if (workspace == null)
            {
                MessageBox.Show("无法打开该工作空间！");
                return;
            }
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
            IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(fileName);
            if (featureClass == null)
            {
                MessageBox.Show("无法打开该矢量数据集！");
                return;
            }
            IFeatureLayer featureLayer = new FeatureLayerClass();
            featureLayer.FeatureClass = featureClass;
            featureLayer.Name = featureClass.AliasName;
            ILayer layer = featureLayer as ILayer;
            axMapControl1.Map.AddLayer(layer);
            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

        }

    

        private void AddRasterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "raster文件（*.tif）|*.tif";

            DialogResult dialogResult = openFileDialog.ShowDialog();
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            string filePath = openFileDialog.FileName;

            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            string folder = System.IO.Path.GetDirectoryName(filePath);
            string fileName = System.IO.Path.GetFileName(filePath);

            // 打开工作空间
            IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(folder, 0);
            if (rasterWorkspace == null)
            {
                MessageBox.Show("无法打开工作空间！");
                return;
            }

            // 打开栅格数据集
            IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(fileName);
            if (rasterDataset == null)
            {
                MessageBox.Show("无法打开栅格数据集！");
                return;
            }

            // 创建栅格图层
            IRasterLayer rasterLayer = new RasterLayerClass();
            rasterLayer.CreateFromDataset(rasterDataset);
            ILayer layer = rasterLayer as ILayer;
            axMapControl1.Map.AddLayer(layer);
            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

        }

        private void simpleRenderMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index);
            if (tocChoosedLayer is IFeatureLayer)
            {
                //defineSImpleRender(tocChoosedLayer as IFeatureLayer);
                RenderSettingsForm renderForm = new RenderSettingsForm(tocChoosedLayer as IFeatureLayer);
                if (renderForm.ShowDialog() == DialogResult.OK)
                {
                    axMapControl1.Refresh();
                    MessageBox.Show("渲染设置应用成功！");
                }
            }
        
            else
            {
                MessageBox.Show("未选择图层，或图层非矢量图层！");
                return;
            }
        }
        private void defineSImpleRender(IFeatureLayer featureLayer)
        {
            IRgbColor color = new RgbColor();
            color.Red = 255;
            color.Blue = 150;
            color.Green = 0;
            //设置符号属性
            ISimpleFillSymbol simpleFeatureSymbol = new SimpleFillSymbol();
            simpleFeatureSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
            simpleFeatureSymbol.Outline.Width = 0.4;
            simpleFeatureSymbol.Color = color as IColor;

            ISimpleRenderer simpleRenderer = new SimpleRendererClass();
            simpleRenderer.Symbol = simpleFeatureSymbol as ISymbol;

            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = simpleRenderer as IFeatureRenderer;
            axMapControl1.Refresh();

        }

      

        private void singleValueRenderMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index
            );

            if (tocChoosedLayer is IFeatureLayer)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(tocChoosedLayer as IFeatureLayer);
                DialogResult dialogResult = fieldSelectDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    defineUniqueValueRender(tocChoosedLayer as IFeatureLayer, fieldSelectDialog.selectFieldName());
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }

        }
        private void defineUniqueValueRender(IFeatureLayer featureLayer, string fieldName)
        {
            // 设置颜色列表，用于随机生成颜色（用于填充面状要素）
            // 设置颜色的基本属性，包括色调（H）、饱和度（S）以及亮度（V）
            IRandomColorRamp colorRamp = new RandomColorRamp();
            colorRamp.StartHue = 76;
            colorRamp.EndHue = 188;
            colorRamp.MinSaturation = 20;
            colorRamp.MaxSaturation = 40;
            colorRamp.MinValue = 85;
            colorRamp.MaxValue = 100;

            colorRamp.UseSeed = true;
            colorRamp.Seed = 43;

            // 设置唯一值渲染的相关属性
            IUniqueValueRenderer valueRender = new UniqueValueRenderer();
            valueRender.FieldCount = 1;
            valueRender.set_Field(0, fieldName);

            // 遍历要素类的所有要素，并为每个要素设置基本的渲染样式
            IFeatureClass featureClass = featureLayer.FeatureClass;
            IFeatureCursor featureCursor = featureClass.Search(null, false);
            IFeature feature = featureCursor.NextFeature();

            // 获取指定字段的索引值
            IFields fields = featureCursor.Fields;
            // 存储字段的索引值
            int iFieldIndex = fields.FindField(fieldName);

            // 为不同的要素，设置不同的填充颜色
            colorRamp.Size = featureClass.FeatureCount(null);
            bool bOK;
            // 判断随机颜色生成是否成功
            colorRamp.CreateRamp(out bOK);

            // 获得随机生成的颜色列表
            IEnumColors enumColors = colorRamp.Colors;
            enumColors.Reset();
            IColor color = enumColors.Next();

            // 开始遍历，为每个要素设置基本的渲染信息
            while (feature != null)
            {
                // 为每个要素设置基本的渲染符号
                ISimpleFillSymbol simpleFillFeature = new SimpleFillSymbolClass();
                simpleFillFeature.Style = esriSimpleFillStyle.esriSFSSolid;
                simpleFillFeature.Outline.Width = 0.4;
                simpleFillFeature.Color = color;

                // 获得当前要素中指定字段的名称
                string featureName = Convert.ToString(feature.get_Value(iFieldIndex));

                // 设置唯一值渲染的相关属性
                valueRender.AddValue(featureName, fieldName, simpleFillFeature as ISymbol);
                valueRender.set_Label(featureName, featureName);
                valueRender.set_Symbol(featureName, simpleFillFeature as ISymbol);

                // 获得下一组要素和颜色
                feature = featureCursor.NextFeature();
                color = enumColors.Next();
            }

            // 接口转换，对渲染方式进行设置
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = valueRender as IFeatureRenderer;

            // 地图刷新
            axMapControl1.Refresh();
        }


        private void FeatureAttributeMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();

            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index);

            // 检查是否选中了图层
            if (tocChoosedItem == esriTOCControlItem.esriTOCControlItemLayer &&
                tocChoosedLayer is IFeatureLayer featureLayer)
            {
                // 创建并显示属性表控件
                var attrForm = new FeatureAttributeTable(featureLayer);
                attrForm.Show(); // 显示包含数据的窗体
            }
            else
            {
                MessageBox.Show("请先选择一个要素图层。");
            }

        }
        private MyMxdDocClass myMxdDoc = new MyMxdDocClass();
       

        private void NewMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            myMxdDoc.newMapDoc(axMapControl1);
        }

        private void OpenMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            myMxdDoc.openMapDoc(axMapControl1);
        }

        private void SaveMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            myMxdDoc.saveMapDoc(axMapControl1);
        }

        private void SaveAsMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            myMxdDoc.SaveAsMapDoc(axMapControl1);
        }

       

      

        private void AxMapControl1_OnAfterDraw(object sender, IMapControlEvents2_OnAfterDrawEvent e)
        {
            // 主地图有地图或图层的时候鹰眼图加载图层
            if (axMapControl1.LayerCount > 0)
            {
                // 先清除鹰眼图的地图
                axMapControlHawkeye.ClearLayers();

                // 图层自下而上加载，防止压盖顺序错误
                for (int i = axMapControl1.Map.LayerCount - 1; i >= 0; i--)
                {
                    axMapControlHawkeye.AddLayer(axMapControl1.get_Layer(i));
                }

                // 设置鹰眼地图与主地图相同空间参考系
                // 防止由于图层放置顺序改变而改变了鹰眼的空间参考系
                axMapControlHawkeye.SpatialReference = axMapControl1.SpatialReference;
                // 设置鹰眼的显示范围为完整显示（FullExtent）
                axMapControlHawkeye.Extent = axMapControlHawkeye.FullExtent;
                // 每次加载或删除图层之后都需要刷新鹰眼图
                axMapControlHawkeye.ActiveView.Refresh();
            }

        }

        private void AxMapControl1_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
        { // 得到新的范围
            IEnvelope envelop = e.newEnvelope as IEnvelope;
            IGraphicsContainer graphicsContainer = axMapControlHawkeye.Map as IGraphicsContainer;
            IActiveView activeView = graphicsContainer as IActiveView;

            // 在绘制前，清除鹰眼图中的任何图形元素
            graphicsContainer.DeleteAllElements();
            IRectangleElement rectangleElement = new RectangleElementClass();
            IElement element = rectangleElement as IElement;
            element.Geometry = envelop;

            // 设置鹰眼图中的红色线框
            IRgbColor frameColor = new RgbColorClass();
            frameColor.Red = 255;
            frameColor.Green = 0;
            frameColor.Blue = 0;
            frameColor.Transparency = 255;

            // 设置鹰眼图中的可视区域的填充颜色
            IRgbColor fillColor = new RgbColorClass();
            fillColor.Red = 255;
            fillColor.Green = 0;
            fillColor.Blue = 0;
            fillColor.Transparency = 0;

            // 产生一个线符号对象
            ILineSymbol outline = new SimpleLineSymbolClass();
            outline.Width = 2;
            outline.Color = frameColor;

            // 设置符号的填充属性
            IFillSymbol fillSymbol = new SimpleFillSymbolClass();
            fillSymbol.Color = fillColor;
            fillSymbol.Outline = outline;
            IFillShapeElement fillShapeElement = element as IFillShapeElement;
            fillShapeElement.Symbol = fillSymbol;
            graphicsContainer.AddElement((IElement)fillShapeElement, 0);

            // 刷新
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

        }

        private void AxMapControlHawkeye_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
           
                if (axMapControlHawkeye.LayerCount > 0)
                {

                    // 如果是鼠标左键
                    if (e.button == 1)
                    {
                        axMapControlHawkeye.Refresh();
                        // 捕捉鼠标单击时的地图坐标
                        IPoint point = new PointClass();
                        point.PutCoords(e.mapX, e.mapY);
                        // 将地图的中心点移动到鼠标点击的点
                        axMapControl1.CenterAt(point);
                        axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                    }
                    else if (e.button == 2) // 如果是鼠标右键
                    {
                        // 鹰眼地图的TrackRectAngle方法，随着鼠标的拖动得到一个矩形框
                        IEnvelope envelop = axMapControlHawkeye.TrackRectangle();
                        axMapControl1.Extent = envelop;
                        axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                    }

                }
            

        }

        private void AxMapControlHawkeye_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            if (e.button == 1)
            {
                axMapControlHawkeye.Refresh();
                // 捕捉鼠标单击时的地图坐标
                IPoint point = new PointClass();
                point.PutCoords(e.mapX, e.mapY);
                // 将地图的中心点移动到鼠标点击的点
                axMapControl1.CenterAt(point);
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
        }

       

        private void AxTOCControl1_OnDoubleClick(object sender, ITOCControlEvents_OnDoubleClickEvent e)
        {
            esriTOCControlItem tocControllerItem = esriTOCControlItem.esriTOCControlItemNone;
            ILayer layer = null;
            IBasicMap basicMap = null;
            object unk = null;
            object data = null;

            if (e.button == 1)
            { // 左键
                axTOCControl1.GetSelectedItem(
                    ref tocControllerItem,
                    ref basicMap,
                    ref layer,
                    ref unk,
                    ref data
                );

                if (tocControllerItem == esriTOCControlItem.esriTOCControlItemLegendClass)
                {
                    ESRI.ArcGIS.Carto.ILegendClass legendClass = new LegendClass();
                    ESRI.ArcGIS.Carto.ILegendGroup legendGroup = new LegendGroupClass();

                    if (unk is ILegendGroup)
                    {
                        legendGroup = unk as ILegendGroup;
                    }

                    legendClass = legendGroup.get_Class((int)data);
                    SymbolSelectDialog symbolSelectDilaog = new SymbolSelectDialog(legendClass, layer);
                    if (symbolSelectDilaog.ShowDialog() == DialogResult.OK)
                    {
                        legendClass.Symbol = symbolSelectDilaog.m_symbol;
                        this.axMapControl1.ActiveView.Refresh();
                        this.axTOCControl1.Refresh();
                    }
                }
            }
        }

        /// <summary>
        /// 根据屏幕像素计算实际的地理距离
        /// </summary>
        /// <param name="activeView">屏幕视图</param>
        /// <param name="pixelUnit">像素个数</param>
        /// <returns></returns>
        private double convertPixelToMapUnits(IActiveView activeView, double pixelUnits)
        {
            double realWorldDisplayExtent;
            int pixelExtent;
            double sizeOfOnePixel;
            double mapUnits;

            // 获取设备中视图显示宽度，即像素个数
            pixelExtent = activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().right
                - activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().left;
            // 获取地图坐标系中的地图显示范围
            realWorldDisplayExtent = activeView.ScreenDisplay.DisplayTransformation.VisibleBounds.Width;
            // 每个像素大小代表的实际距离
            sizeOfOnePixel = realWorldDisplayExtent / pixelExtent;
            // 地理距离
            mapUnits = pixelUnits * sizeOfOnePixel;

            return mapUnits;
        }

        public class Display
        {
            private string _title;
            private string _content;
            private string _fieldname;

            public Display(string title, string fieldname,string content)
            {
                _title = title;
                _content = content;
                _fieldname = fieldname;
            }

            [Category("显示信息")]
            [Description("显示内容的标题")]
            [DisplayName("标题")]
            public string Title
            {
                get { return _title; }
                set { _title = value; }
            }

            [Category("显示信息")]
            [Description("具体显示的字段名")]
            [DisplayName("字段名")]
            public string Fieldname
            {
                get { return _fieldname; }
                set { _fieldname = value; }
            }
            [Category("显示信息")]
            [Description("具体显示的属性值")]
            [DisplayName("属性值")]
            public string Content
            {
                get { return _content; }
                set { _content = value; }
            }
            
           

            [Category("统计信息")]
            [Description("内容中的项目数量")]
            [DisplayName("项目数量")]
            public int ItemCount
            {
                get
                {
                    if (string.IsNullOrEmpty(_content))
                        return 0;
                    return _content.Split('、').Length;
                }
            }

            [Category("统计信息")]
            [Description("显示时间")]
            [DisplayName("更新时间")]
            public DateTime UpdateTime { get; set; } = DateTime.Now;
        }

        
        public void DisplayInPropertyGrid(string content, string fieldname,string title = "查询结果")
        {
            try
            {
                Display display = new Display(title, fieldname,content)
                {
                    UpdateTime = DateTime.Now
                };

                propertyGrid1.SelectedObject = display;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"显示内容时出错：{ex.Message}");
            }
        }
        private string query(AxMapControl mapControl, IFeatureLayer featureLayer, IGeometry geometry, string fieldName)
        {
            mapControl.Map.ClearSelection();

            IFeatureClass featureClass = featureLayer.FeatureClass;
            if (featureClass == null)
            {
                return null;
            }

            // 初始化空间过滤器
            ISpatialFilter spatialFilter = new SpatialFilterClass();
            spatialFilter.Geometry = geometry;

            // 根据图层类型选择缓冲方式
            switch (featureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    break;
            }

            // 定义空间过滤器的空间字段
            spatialFilter.GeometryField = featureClass.ShapeFieldName;

            // 利用要素过滤器查询要素
            IQueryFilter queryFilter = spatialFilter as IQueryFilter;
            IFeatureCursor featureCursor = featureLayer.Search(queryFilter, true);
            IFeature feature = featureCursor.NextFeature();

            string szNames = null;
            while (feature != null)
            {
                // 选择指定要素
                int fieldIndex = feature.Fields.FindField(fieldName);
                // 获取要素名称
                szNames += feature.get_Value(fieldIndex) + "、";

                mapControl.Map.SelectFeature(featureLayer as ILayer, feature);
                mapControl.ActiveView.Refresh();
                feature = featureCursor.NextFeature();
            }
            return szNames;
        }

        private void PointQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 1;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }

        }

        private void ShowPropertyTab()
        {
            try
            {
                TAB.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"切换选项卡失败: {ex.Message}");
            }
        }
        private void AxMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (m_iMouseFlag == 0)
            {
                return;
            }

            string szNames =null;
            if (m_iMouseFlag == 1)
            {
                // 获取视图范围
                IActiveView activeView = this.axMapControl1.ActiveView;
                // 获取鼠标点击屏幕坐标
                IPoint point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                // 屏幕距离转换为地图距离
                double dLength = convertPixelToMapUnits(activeView, 2);

                // 根据缓冲区半径生成空间过滤器
                ITopologicalOperator topoOperator = point as ITopologicalOperator;
                IGeometry geoBuffer = topoOperator.Buffer(dLength);

                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), geoBuffer, m_szFieldName);
            }
            else if (m_iMouseFlag == 2)//线查询
            {
                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), this.axMapControl1.TrackLine(), m_szFieldName);
            }
            else if (m_iMouseFlag == 3)//矩形查询
            {
                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), this.axMapControl1.TrackRectangle(), m_szFieldName);
            }
            else if (m_iMouseFlag == 4)//圆查询
            {
                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), this.axMapControl1.TrackCircle(), m_szFieldName);
            }
            string result = szNames.Substring(0, szNames.Length - 1);
            DisplayInPropertyGrid(result, m_szFieldName);
            ShowPropertyTab();
        }
        public IFeatureLayer getSelectedFeatureLayer()
        {
                esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
                IBasicMap basicMap = null;
                ILayer tocChoosedLayer = null;
                object other = new object();
                object index = new object();
                axTOCControl1.GetSelectedItem(
                    ref tocChoosedItem,
                    ref basicMap,
                    ref tocChoosedLayer,
                    ref other,
                    ref index
                );

            if (tocChoosedLayer is IFeatureLayer featurelayer)
            {
                IFeatureClass featureClass = featurelayer.FeatureClass;
                if (featureClass != null)
                {
                    return featurelayer;
                }
                else return null;
            }
            else return null;
        }

        private void LineQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 2;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }

        }

        private void CircleQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 4;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void RectangleQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 3;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

       
            private void CloseQueryToolStripMenuItem_Click(object sender, EventArgs e)
            {
                try
                {
                    IMapControl3 mapControl = axMapControl1.Object as IMapControl3;

                    //清除选择集并重绘地图
                    if (mapControl?.Map != null)
                    {
                        //使用Map的ClearSelection方法
                        mapControl.Map.ClearSelection();

                        // 使用IFeatureSelection
                        for (int i = 0; i < mapControl.Map.LayerCount; i++)
                        {
                            ILayer layer = mapControl.Map.get_Layer(i);
                            if (layer is IFeatureLayer featureLayer)
                            {
                                IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
                                featureSelection?.Clear();
                            }
                        }

                        // 重绘地图
                        mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, mapControl.ActiveView.Extent);
                    }

                    //将鼠标样式设置为指针模式
                    axMapControl1.MousePointer = esriControlsMousePointer.esriPointerArrow;
                   

                    //将m_iMouseFlag的值设置为0
                    m_iMouseFlag = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"关闭查询工具时出错: {ex.Message}");
                }
            }

        private void BarChartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查当前是否有激活的地图
                if (axMapControl1.Map == null || axMapControl1.Map.LayerCount == 0)
                {
                    MessageBox.Show("请先加载地图数据！", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
                IBasicMap basicMap = null;
                ILayer currentLayer = null;
                object other = new object();
                object index = new object();
                axTOCControl1.GetSelectedItem(
                    ref tocChoosedItem,
                    ref basicMap,
                    ref currentLayer,
                    ref other,
                    ref index
                );

                if (currentLayer is IFeatureLayer)
                {
                 
                }
                else
                {
                    MessageBox.Show("未选择图层！");
                    return;
                }

                

                // 检查图层是否为要素图层
                IFeatureLayer featureLayer = currentLayer as IFeatureLayer;
                if (featureLayer == null)
                {
                    MessageBox.Show("当前选择的图层不是要素图层！", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 获取要素类
                IFeatureClass featureClass = featureLayer.FeatureClass;
                if (featureClass == null)
                {
                    MessageBox.Show("无法获取要素类信息！", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 检查要素类是否有要素
                if (featureClass.FeatureCount(null) == 0)
                {
                    MessageBox.Show("选中的图层没有要素数据！", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 创建并显示柱状图对话框
                BarChart barChartForm = new BarChart();

                // 设置要素类到对话框
                barChartForm.SetFeatureClass(featureClass);

                // 设置对话框标题显示当前图层名
                barChartForm.Text = $"制作柱状图 - {currentLayer.Name}";

                // 显示对话框
                DialogResult result = barChartForm.ShowDialog();

                // 处理用户选择
                if (result == DialogResult.OK)
                {
                    // 获取用户选择的字段
                    List<string> selectedFields = barChartForm.GetSelectedFields();

                    if (selectedFields.Count == 0)
                    {
                        MessageBox.Show("请至少选择一个数值字段！", "提示",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    int chartWidth = barChartForm.GetChartWidth();
                    int chartHeight = barChartForm.GetChartHeight();

                    // 调用生成柱状图函数，传递所有参数
                    GenerateBarChart(featureClass, selectedFields, currentLayer.Name, chartWidth, chartHeight);
                }
               

                // 释放资源
                barChartForm.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开柱状图功能时出错：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
         }

        private void GenerateBarChart(IFeatureClass featureClass, List<string> selectedFields, string layerName, int chartWidth, int chartHeight)
        {
            try
            {
                // 清除旧的柱状图图层
                ClearOldBarChartLayers(layerName);

                // 创建新的柱状图图层
                IFeatureLayer chartLayer = new FeatureLayerClass();
                chartLayer.FeatureClass = featureClass;
                chartLayer.Name = layerName + "_柱状图"; // 与清除逻辑对应
                chartLayer.Visible = true;

                // 应用柱状图渲染器
                DefineBarChartRenderer(chartLayer, selectedFields, chartWidth, chartHeight);

                // 添加新图层到地图
                IMap map = axMapControl1.Map;
                map.AddLayer(chartLayer);

                // 刷新地图显示
                axMapControl1.ActiveView.Refresh();
                axTOCControl1.Refresh();

                MessageBox.Show($"柱状图生成成功！\n图层：{chartLayer.Name}\n字段数：{selectedFields.Count}",
                    "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成柱状图时出错：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void DefineBarChartRenderer(IFeatureLayer featureLayer, List<string> fieldNames, int symbolWidth, int symbolHeight)
        {
           
            IChartRenderer chartRenderer = new ChartRendererClass();
            IRendererFields rendererFields = chartRenderer as IRendererFields;
            rendererFields.ClearFields(); // 清空原有字段

            // 为渲染器添加选中的字段（设置字段名和别名）
            IFeatureClass featureClass = featureLayer.FeatureClass;
            foreach (string fieldName in fieldNames)
            {
                int fieldIndex = featureClass.Fields.FindField(fieldName);
                if (fieldIndex < 0) continue; // 跳过无效字段
                string alias = featureClass.Fields.get_Field(fieldIndex).AliasName;
                rendererFields.AddField(fieldName, string.IsNullOrEmpty(alias) ? fieldName : alias);
            }
           

            
            double maxValue = 0;
            foreach (string fieldName in fieldNames)
            {
                double fieldMax = GetFieldMaxValue(featureClass, fieldName);
                if (fieldMax > maxValue) maxValue = fieldMax;
            }
            if (maxValue <= 0) maxValue = 1; // 避免除数为0
           
            // 创建柱状图符号
            IBarChartSymbol barChartSymbol = new BarChartSymbolClass();
            IChartSymbol chartSymbol = barChartSymbol as IChartSymbol;
            chartSymbol.MaxValue = maxValue; // 绑定最大值（柱状图高度比例依据）

            // 设置符号整体尺寸
            IMarkerSymbol markerSymbol = barChartSymbol as IMarkerSymbol;
            markerSymbol.Size = symbolHeight; // 柱状图最大高度
            barChartSymbol.Width = symbolWidth; // 柱宽（修正：正确属性名）

            // 为每个字段分配独立颜色（使用随机色阶）
            ISymbolArray symbolArray = barChartSymbol as ISymbolArray;
         

            // 生成随机颜色
            IRandomColorRamp colorRamp = new RandomColorRampClass();
            colorRamp.StartHue = 76;
            colorRamp.EndHue = 188;
            colorRamp.MinSaturation = 20;
            colorRamp.MaxSaturation = 40;
            colorRamp.MinValue = 85;
            colorRamp.MaxValue = 100;
            colorRamp.Size = fieldNames.Count;
            colorRamp.UseSeed = true;
            colorRamp.Seed = 43;

            bool colorRampOK;
            colorRamp.CreateRamp(out colorRampOK);
            IEnumColors enumColors = colorRamp.Colors;
            enumColors.Reset();

            // 为每个字段添加柱状符号（直接添加，无需清空原有）
            foreach (string fieldName in fieldNames)
            {
                IColor color = enumColors.Next();
                ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass();
                fillSymbol.Color = color;
                fillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                fillSymbol.Outline.Width = 0.2; // 柱子边框宽度
                symbolArray.AddSymbol(fillSymbol as ISymbol);
            }

            

            // 设置渲染器属性：符号居中显示
            chartRenderer.UseOverposter = true; // 使符号位于要素几何中心
            chartRenderer.ChartSymbol = barChartSymbol as IChartSymbol; // 绑定符号

            // 绑定到要素图层
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = chartRenderer as IFeatureRenderer;

            // 刷新地图和TOC控件
            axMapControl1.ActiveView.Refresh();
            axTOCControl1.Refresh();
            
        }

        private void ClearOldBarChartLayers(string originalLayerName)
        {
            IMap map = axMapControl1.Map;
            for (int i = map.LayerCount - 1; i >= 0; i--)
            {
                ILayer layer = map.get_Layer(i);
                if (layer.Name == originalLayerName + "_柱状图")
                {
                    map.DeleteLayer(layer);
                }
            }
        }
        private double GetFieldMaxValue(IFeatureClass featureClass, string fieldName)
        {
            try
            {
                IDataStatistics dataStats = new DataStatisticsClass();
                IFeatureCursor cursor = featureClass.Search(null, false);
                dataStats.Field = fieldName;
                dataStats.Cursor = cursor as ICursor;

                IStatisticsResults statsResults = dataStats.Statistics;
                return statsResults.Maximum; // 返回字段最大值
            }
            catch
            {
                return 0; // 字段为空或错误时返回0
            }
        }
        private void PieChartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查当前是否有激活的地图（与柱状图相同）
                if (axMapControl1.Map == null || axMapControl1.Map.LayerCount == 0)
                {
                    MessageBox.Show("请先加载地图数据！", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
                IBasicMap basicMap = null;
                ILayer currentLayer = null;
                object other = new object();
                object index = new object();
                axTOCControl1.GetSelectedItem(
                    ref tocChoosedItem,
                    ref basicMap,
                    ref currentLayer,
                    ref other,
                    ref index
                );

                if (!(currentLayer is IFeatureLayer))
                {
                    MessageBox.Show("未选择图层！");
                    return;
                }

                // 检查图层是否为要素图层
                IFeatureLayer featureLayer = currentLayer as IFeatureLayer;
                if (featureLayer == null)
                {
                    MessageBox.Show("当前选择的图层不是要素图层！", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 获取要素类
                IFeatureClass featureClass = featureLayer.FeatureClass;
                if (featureClass == null)
                {
                    MessageBox.Show("无法获取要素类信息！", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 检查要素类是否有要素
                if (featureClass.FeatureCount(null) == 0)
                {
                    MessageBox.Show("选中的图层没有要素数据！", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 创建并显示饼图对话框（复用柱状图对话框或创建新的）
                BarChart pieChartForm = new BarChart(); // 可以复用或创建专门的PieChart窗体

                // 设置要素类到对话框
                pieChartForm.SetFeatureClass(featureClass);

                // 设置对话框标题显示当前图层名
                pieChartForm.Text = $"制作饼图 - {currentLayer.Name}";

                // 显示对话框
                DialogResult result = pieChartForm.ShowDialog();

                // 处理用户选择
                if (result == DialogResult.OK)
                {
                    // 获取用户选择的字段
                    List<string> selectedFields = pieChartForm.GetSelectedFields();

                    if (selectedFields.Count == 0)
                    {
                        MessageBox.Show("请至少选择一个数值字段！", "提示",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    int chartWidth = pieChartForm.GetChartWidth();
                    int chartHeight = pieChartForm.GetChartHeight();

                    // 调用生成饼图函数
                    GeneratePieChart(featureClass, selectedFields, currentLayer.Name, chartWidth, chartHeight);
                }

                // 释放资源
                pieChartForm.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开饼图功能时出错：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GeneratePieChart(IFeatureClass featureClass, List<string> selectedFields, string layerName, int chartWidth, int chartHeight)
        {
            try
            {
                // 清除旧的饼图图层
                ClearOldPieChartLayers(layerName);

                // 创建新的饼图图层
                IFeatureLayer chartLayer = new FeatureLayerClass();
                chartLayer.FeatureClass = featureClass;
                chartLayer.Name = layerName + "_饼图"; // 与清除逻辑对应
                chartLayer.Visible = true;

                // 应用饼图渲染器
                DefinePieChartRenderer(chartLayer, selectedFields, chartWidth, chartHeight);

                // 添加新图层到地图
                IMap map = axMapControl1.Map;
                map.AddLayer(chartLayer);

                // 刷新地图显示
                axMapControl1.ActiveView.Refresh();
                axTOCControl1.Refresh();

                MessageBox.Show($"饼图生成成功！\n图层：{chartLayer.Name}\n字段数：{selectedFields.Count}",
                    "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成饼图时出错：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DefinePieChartRenderer(IFeatureLayer featureLayer, List<string> fieldNames, int symbolWidth, int symbolHeight)
        {
            IChartRenderer chartRenderer = new ChartRendererClass();
            IRendererFields rendererFields = chartRenderer as IRendererFields;
            rendererFields.ClearFields(); // 清空原有字段

            // 为渲染器添加选中的字段
            IFeatureClass featureClass = featureLayer.FeatureClass;
            foreach (string fieldName in fieldNames)
            {
                int fieldIndex = featureClass.Fields.FindField(fieldName);
                if (fieldIndex < 0) continue; // 跳过无效字段
                string alias = featureClass.Fields.get_Field(fieldIndex).AliasName;
                rendererFields.AddField(fieldName, string.IsNullOrEmpty(alias) ? fieldName : alias);
            }

            // 创建饼图符号
            IPieChartSymbol pieChartSymbol = new PieChartSymbolClass();
            IChartSymbol chartSymbol = pieChartSymbol as IChartSymbol;

            // 设置符号尺寸
            IMarkerSymbol markerSymbol = pieChartSymbol as IMarkerSymbol;
            markerSymbol.Size = Math.Max(symbolWidth, symbolHeight); // 饼图直径

            // 为每个字段分配颜色
            ISymbolArray symbolArray = pieChartSymbol as ISymbolArray;

            // 生成随机颜色
            IRandomColorRamp colorRamp = new RandomColorRampClass();
            colorRamp.StartHue = 76;
            colorRamp.EndHue = 188;
            colorRamp.MinSaturation = 20;
            colorRamp.MaxSaturation = 40;
            colorRamp.MinValue = 85;
            colorRamp.MaxValue = 100;
            colorRamp.Size = fieldNames.Count;
            colorRamp.UseSeed = true;
            colorRamp.Seed = 43;

            bool colorRampOK;
            colorRamp.CreateRamp(out colorRampOK);
            IEnumColors enumColors = colorRamp.Colors;
            enumColors.Reset();

            // 为每个字段添加颜色符号
            foreach (string fieldName in fieldNames)
            {
                IColor color = enumColors.Next();
                ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass();
                fillSymbol.Color = color;
                fillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                fillSymbol.Outline.Width = 0.2;
                symbolArray.AddSymbol(fillSymbol as ISymbol);
            }

            // 设置饼图属性
            pieChartSymbol.Clockwise = true; // 顺时针方向
            pieChartSymbol.UseOutline = true; // 使用轮廓

            // 设置渲染器属性
            chartRenderer.UseOverposter = true;
            chartRenderer.ChartSymbol = pieChartSymbol as IChartSymbol;

            // 绑定到要素图层
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = chartRenderer as IFeatureRenderer;

            // 刷新地图和TOC控件
            axMapControl1.ActiveView.Refresh();
            axTOCControl1.Refresh();
        }

        private void ClearOldPieChartLayers(string originalLayerName)
        {
            IMap map = axMapControl1.Map;
            for (int i = map.LayerCount - 1; i >= 0; i--)
            {
                ILayer layer = map.get_Layer(i);
                if (layer.Name == originalLayerName + "_饼图")
                {
                    map.DeleteLayer(layer);
                }
            }
        }

    }
}


